package servlet;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import pojo.User;
import service.UserHandleService;
import service.impl.UserHandleServiceImpl;
import utils.Format;
import utils.StreamConvertTool;
public class LoginServlet extends HttpServlet {
	UserHandleService uhs = new UserHandleServiceImpl();
//	User user = new User();
    public LoginServlet() {
        super();
    }
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setSizeMax(2000*1024);
		List items = null;
		try {
			items = upload.parseRequest(request);
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
		Iterator iter = items.iterator();
		String[] str = new String[4];
		byte[] bytes = new byte[2048000];
		while (iter.hasNext()) {
			FileItem item = (FileItem) iter.next();
			if (item.isFormField()) {  
				String name = item.getFieldName();
				String value = item.getString("utf-8"); 
				System.out.println(name+"......"+value);
				if("uname".equals(name)){
					str[0] = value;
				}else if("sal".equals(name)){
					str[1] = value;
				}else if("birth".equals(name)){
					str[2] = value;
					if(!Format.verifyBirth(value)){
						response.sendRedirect("errorformat");
						return;
					}
				}else if("sex".equals(name)){
					str[3] = value;
				}
			} else {
				String fieldName = item.getFieldName(); 
				long size = item.getSize();
				if(size>2048000){
					response.sendRedirect("errorSize");
					return;
				}
				try {
//					item.write(saveFile);// 把上传的内容写到一个文件中
					InputStream in = item.getInputStream();
					bytes = StreamConvertTool.InputStreamToByteArray(in);
					in.close();
				} catch (Exception e) {
					e.printStackTrace();
				} 
				
			}
			
		}
		uhs.addUser(str[0], str[1], str[2], str[3], bytes);
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter writer = response.getWriter();
		writer.write("<h2>插入数据成功</h2><br/>");
		writer.write("<a href='http://localhost:8080/weekfour_day01_homework/show'>点击查看所有用户</a>");
		
//		request.getRequestDispatcher("/show").forward(request, response);
	}

}
